﻿using System;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using YiSha.Util;
using YiSha.Util.Extension;
using YiSha.Util.Model;
using YiSha.Data;
using YiSha.Data.Repository;
using YiSha.Entity.ExperimentManage;
using YiSha.Model.Param.ExperimentManage;

namespace YiSha.Service.ExperimentManage
{
    /// <summary>
    /// 创 建：admin
    /// 日 期：2020-04-21 03:30
    /// 描 述：服务类
    /// </summary>
    public class ExperimentDataService :  RepositoryFactory
    {
        #region 获取数据
        public async Task<List<ExperimentDataEntity>> GetList(ExperimentDataListParam param)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression);
            return list.ToList();
        }

        public async Task<List<ExperimentDataEntity>> GetPageList(ExperimentDataListParam param, Pagination pagination)
        {
            var expression = ListFilter(param);
            var list= await this.BaseRepository().FindList(expression, pagination);
            return list.ToList();
        }

        public async Task<ExperimentDataEntity> GetEntity(long id)
        {
            return await this.BaseRepository().FindEntity<ExperimentDataEntity>(id);
        }
        #endregion

        #region 提交数据
        public async Task SaveForm(ExperimentDataEntity entity)
        {
            if (entity.Id.IsNullOrZero())
            {
                entity.ExperimentNumber = await GetExperimentNo(entity.ExperimentType);
                await entity.Create();
                await this.BaseRepository().Insert(entity);
            }
            else
            {
                await entity.Modify();
                await this.BaseRepository().Update(entity);
            }
        }

        public async Task<bool> ChangeStatus(long id, int status, long userId, string ownerType)
        {
            string strSql = string.Format("update `system_experiment_data` set `status` = {1},`{2}`= {3} where id='{0}';",
                id, status, ownerType, userId);
            var result = await this.BaseRepository().ExecuteBySql(strSql);
            return result > 0 ? true : false;
        }

        public async Task DeleteForm(string ids)
        {
            long[] idArr = TextHelper.SplitToArray<long>(ids, ',');
            await this.BaseRepository().Delete<ExperimentDataEntity>(idArr);
        }
        #endregion

        #region 私有方法
        private Expression<Func<ExperimentDataEntity, bool>> ListFilter(ExperimentDataListParam param)
        {
            var expression = LinqExtensions.True<ExperimentDataEntity>();
            if (param != null)
            {
            }
            return expression;
        }

        private List<DbParameter> ListFilter(string experimentNo, StringBuilder strSql)
        {
            strSql.Append(@"SELECT  
experiment_number as ExperimentNumber
                            FROM    system_experiment_data
                            WHERE   experiment_number like '" + experimentNo + "%' order by id desc LIMIT 0,1 ");
            var parameter = new List<DbParameter>();
            return parameter;
        }

        private async Task<string> GetExperimentNo(string expType) 
        {
            string experimentNo = null;
            string type = null;
            switch (expType) 
            {
                case "生物安全柜":
                    type = "CM01";
                    break;
                case "洁净工作台":
                    type = "CM02";
                    break;
            }
            string year = DateTime.Now.Year.ToString();
            string month = DateTime.Now.Month.ToString().PadLeft(2, '0');
            var strSql = new StringBuilder();
            List<DbParameter> filter = ListFilter(experimentNo, strSql);
            var list = await this.BaseRepository()
                .FindList<ExperimentDataEntity>(strSql.ToString(), filter.ToArray());
            List<ExperimentDataEntity> lists = list.ToList();
            if (lists.Count > 0)
            {
                string expNumber = lists[0].ExperimentNumber;
                int number = int.Parse(expNumber.Substring(expNumber.Length - 3));
                experimentNo = type + year + month + (number+1).ToString().PadLeft(3, '0');
            }
            else 
            {
                experimentNo = type + year + month + "001";
            }
            return experimentNo;
        }
        #endregion
    }
}
